﻿using System.Diagnostics;
using System.Reflection;

namespace TiaoTiaoCode.Common.Extensions
{
    public static class ProcessEx
    {
        /// <summary>
        /// 获取当前程序运行进程
        /// 用户通过进程处理单实例启动
        /// </summary>
        /// <returns>有启动的实例则返回对应进程，没有则返回null</returns>
        public static Process? RunningInstance(this Process current)
        {
            var processes = Process.GetProcessesByName(current.ProcessName);

            foreach (var process in processes)
            {
                if (process.Id != current.Id)
                {
                    // 确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") != current.MainModule!.FileName)
                    {
                        return process;
                    }
                }
            }

            return null;
        }
    }
}
